<?php
class Upload {
	private static $cfg = array();		//config
	private static $files = array();	//files
	private static $ret = array();		//return
	private static $error = array();	//error
	
	/**
	 * handle the upload(the entry)
	 * 
	 */
	public static function handle($cfg) {
		self::setCfg($cfg);
		self::setError();
		if(self::$error) return self::$error;
		self::setUpload();
		self::setThumb();
		self::setResize();
		return self::$ret;
	}
	
	private static function setError() {
		foreach(self::$files as $key => $file) {
			self::parseInfo($key, $file);
			self::parseExt($key, $file);
			self::parseSize($key, $file);
			self::parseWritable($key, $file);
		}
	}
	
	private static function setUpload() {
		foreach(self::$files as $key => $file) {
			if(!empty($file['name'])) {
				$dir = rtrim(self::$cfg[$key]['dir'], '/') . '/';
				$ext = UploadUtil::getExt($file['name']);
				//设置保存文件名
				$savename = self::$cfg[$key]['named'] == 1 ? UploadUtil::randStr() : basename($file['name'], $ext);
				if(move_uploaded_file($file['tmp_name'], $dir . $savename.".$ext")) {
					self::$ret[$key]['path'] = realpath($dir . $savename.".$ext");
				}
			}
		}
	}
	
	private static function setThumb() {
		foreach(self::$files as $key => $file) {
			foreach(self::$cfg[$key]['image_thumbs'] as $thumb) {
				$src = self::$ret[$key]['path'];
				$dest = rtrim($thumb[0], '/') . '/' . basename($src);
				$cfg = array(
					'image_resizetype' => 0,
					'image_resizew' => $thumb[1],
					'image_resizeh' => $thumb[2],
					'image_bgcolor' => $thumb[3],
				);
				UploadUtil::thumb($src, $dest, $cfg);
				self::$ret[$key]['thumbs'][] = realpath($dest);
			}
		}
	}
	
	private static function setResize() {
		foreach(self::$files as $key => $file) {
			if(self::$cfg[$key]['image_resize'] && !empty($file['name'])) {
				$src = $dest = self::$ret[$key]['path'];
				UploadUtil::thumb($src, $dest, self::$cfg[$key]);
			}
		}
	}
	
	private static function parseInfo($key, $file) {
		$errorinfos = array(
			1 => 'Exceed upload_max_filesize in php.ini setting',
			2 => 'Exceed MAX_FILE_SIZE in html',
			3 => 'Upload part of the file',
			6 => 'Can not find the temp directory',
			7 => 'File write fail',
		);
		//if not allow empty then and this one
		if(self::$cfg[$key]['notnull']) {
			$errorinfos[4] = 'No file upload';
		}
		
		if(isset($errorinfos[$file['error']])) self::$error[] = $errorinfos[$file['error']].":".self::$cfg[$key]['desc'];
	}
	
	/**
	 *
	 */
	private static function parseExt($key, $file) {
		$ext = empty($file['name']) ? '' : UploadUtil::getExt($file['name']);
		$allowExt = self::$cfg[$key]['allowtypes'];
		if($ext !== '' && FALSE === strpos($allowExt, $ext)) {
			self::$error[] = 'Type must be '.$allowExt.' :'.self::$cfg[$key]['desc'];
		}
	}
	
	/**
	 *
	 */
	private static function parseSize($key, $file) {
		$maxsize = self::$cfg[$key]['maxsize'];
		if($file['size'] > $maxsize) {
			self::$error[] = 'Max size is '.$maxsize.' :'.self::$cfg[$key]['desc'];
		}
	}
	
	/**
	 *
	 */
	private static function parseWritable($key, $file) {
		$dir = self::$cfg[$key]['dir'];
		if(!UploadUtil::isReallyWritable($dir)) {
			self::$error[] = 'Can not write to '.$dir.' :'.self::$cfg[$key]['desc'];
		}
		//check thumb directory really writable
		foreach(self::$cfg[$key]['image_thumbs'] as $thumb) {
			if(!UploadUtil::isReallyWritable($thumb[0])) {
				self::$error[] = 'Can not write to thumb directory '.$thumb[0].' :'.self::$cfg[$key]['desc'];
			}
		}
	}
	
	/**
	 * set config
	 */
	private static function setCfg($cfg) {
		//default config
		$icfg = require FRAMEWORK_UPLOAD_ROOT . 'config.php';
		//init and set config
		foreach($_FILES as $k => $v) {
			if(is_array($v['name'])) {
				foreach($v['name'] as $f_k => $f_v) {
					self::$files["{$k}_{$f_k}"]['name'] = $v['name'][$f_k];
					self::$files["{$k}_{$f_k}"]['type'] = $v['type'][$f_k];
					self::$files["{$k}_{$f_k}"]['tmp_name'] = $v['tmp_name'][$f_k];
					self::$files["{$k}_{$f_k}"]['error'] = $v['error'][$f_k];
					self::$files["{$k}_{$f_k}"]['size'] = $v['size'][$f_k];
					self::$ret["{$k}_{$f_k}"] = array(
						'path' => '',
						'thumbs' => array(),
					);
					self::$cfg["{$k}_{$f_k}"] = $icfg;
					if(is_array($cfg["{$k}_{$f_k}"])) {
						foreach($cfg["{$k}_{$f_k}"] as $c_k => $c_v) {
							if(array_key_exists($c_k, self::$cfg["{$k}_{$f_k}"])) self::$cfg["{$k}_{$f_k}"][$c_k] = $c_v;
						}
					}
				}
			} else {
				self::$files[$k] = $v;
				self::$ret[$k] = array(
					'path' => '',
					'thumbs' => array(),
				);
				self::$cfg[$k] = $icfg;
				if(is_array($cfg[$k])) {
					foreach($cfg[$k] as $c_k => $c_v) {
						if(array_key_exists($c_k, self::$cfg[$k])) self::$cfg[$k][$c_k] = $c_v;
					}
				}
			}
		}
	}
}
?>